package org.framework.lazy.cloud.network.heartbeat.server.netty.proxy.socks.advanced;


import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.framework.lazy.cloud.network.heartbeat.common.NettyTransferChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyChannelContext;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.payload.NettyProxyMsg;
import org.framework.lazy.cloud.network.heartbeat.common.advanced.proxy.socks.server.AbstractHandleSocksReportClientProxyClientOtherConnectionTransferSuccessTypeAdvanced;
import org.framework.lazy.cloud.network.heartbeat.common.constant.ProxyMessageType;
import org.framework.lazy.cloud.network.heartbeat.common.utils.ChannelAttributeKeyUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Role;
import org.springframework.stereotype.Component;
import org.wu.framework.core.utils.ObjectUtils;


@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
@Slf4j
@Component
public class ServerHandleSocksReportClientProxyClientOtherConnectionTransferSuccessTypeAdvanced
        extends AbstractHandleSocksReportClientProxyClientOtherConnectionTransferSuccessTypeAdvanced<NettyProxyMsg> {


    /**
     * 处理当前数据
     *
     * @param nettyChannelContext 当前通道
     * @param nettyProxyMsg       通道数据
     */
    @Override
    public void doHandler(NettyChannelContext nettyChannelContext, NettyProxyMsg nettyProxyMsg) {
        Channel transferChannel = nettyChannelContext.channel();

        // 绑定传输通道
        byte[] visitorId = nettyProxyMsg.getVisitorId();

        // next translation
        Channel nextTransferChannel = NettyTransferChannelContext.getVisitor(visitorId);
        ChannelAttributeKeyUtils.buildTransferNextChannel(nextTransferChannel, transferChannel);
        ChannelAttributeKeyUtils.buildTransferNextChannel(transferChannel, nextTransferChannel);
        // 通知发起方客户端开始数据传输


        if (ObjectUtils.isNotEmpty(nextTransferChannel) && nextTransferChannel.isActive()) {
            NettyProxyMsg startTransfer = new NettyProxyMsg();
            startTransfer.setType(ProxyMessageType.SOCKS_DISTRIBUTE_CLIENT_PROXY_CLIENT_TRANSFER_CONNECTION_SUCCESS_);
            startTransfer.setVisitorId(nettyProxyMsg.getVisitorId());
            nextTransferChannel.writeAndFlush(startTransfer);

        } else {
            log.error("传输通道异常");
        }
    }

}
